package com.shuzi.MediaShare.net;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shuzi.MediaShare.Constant;
import com.shuzi.MediaShare.model.ChargeInfo;
import com.shuzi.MediaShare.model.LoginInfo;
import com.shuzi.MediaShare.model.MediaDownLoadLinkInfo;
import com.shuzi.MediaShare.model.MediaType;
import com.shuzi.MediaShare.model.MovieInfo;
import com.shuzi.MediaShare.utils.Logger;

/**
 * http 协议获取接口
 * 
 * @author lung 下午11:41:44 2013
 */
public class Protocol
{

	/** TAG */
	private static String TAG = "Protocol";

	/** 基礎地址 */
	public static String BASEPATH = "http://183.13.227.109:81/mediaShare/action/";

	// public static String BASEPATH = "http://192.168.1.7:81";

	private static String ACTION = "/mediaShare/action/";

	/** 登陸接口地址 */
	public static String LOGIN = BASEPATH + ACTION + "clogin.php?ID=";

	/** 查询名片地址 */
	public static String QUERY_DESC = BASEPATH + ACTION + "queryDesc.php";

	/** 查询电影发布地址 */
	public static String QUERY_VIDEO = BASEPATH + ACTION + "queryVideo.php";

	/** 自定义 查询电影发布地址 */
	public static String QUERY_VIDEO2 = BASEPATH + ACTION + "cmd.php?cmd=query";

	/** 充值 */
	public static String CHARGE = BASEPATH + ACTION + "cCharge.php";

	/** 扣费 */
	public static String CHARGECELL = BASEPATH + ACTION + "cChargeCell.php";

	/** 发送upd获取ip是否成功 */
	public static boolean getUdpIp = false;

	/**
	 * 重设地址
	 */
	public static void setUrl()
	{
		/** 登陸接口地址 */
		LOGIN = BASEPATH + ACTION + "clogin.php?ID=";

		/** 查询名片地址 */
		QUERY_DESC = BASEPATH + ACTION + "queryDesc.php";

		/** 查询电影发布地址 */
		QUERY_VIDEO = BASEPATH + ACTION + "queryVideo.php";

		/** 自定义 查询电影发布地址 */
		QUERY_VIDEO2 = BASEPATH + ACTION + "cmd.php?cmd=query";

		/** 充值 */
		CHARGE = BASEPATH + ACTION + "cCharge.php";

		/** 扣费 */
		CHARGECELL = BASEPATH + ACTION + "cChargeCell.php";

	}

	/**
	 * 登陆接口
	 * 
	 * @param Id
	 * @return 登陆信息
	 */
	public static LoginInfo login()
	{
		String responseData = getData(LOGIN + Constant.IMEI);
		if (responseData != null)
		{
			try
			{
				JSONObject object = new JSONObject(responseData);
				LoginInfo info = new LoginInfo();
				info.setCode(object.getString("code"));
				info.setMsg(object.getString("msg"));
				info.setUid(object.getString("uid"));
				Constant.UID = info.getUid();
				// Logger logger = Logger.getLogger();
				JSONArray typeJsonObject = new JSONArray(
						object.getString("column"));

				JSONArray typeArray = new JSONArray(object.getString("type"));
				JSONArray areaArray = new JSONArray(object.getString("area"));
				for (int i = 0; i < typeJsonObject.length(); i++)
				{
					MediaType type = new MediaType();
					type.type = typeJsonObject.get(i).toString();
					type.typeId = i;
					type.typeList = typeArray
							.get(i)
							.toString()
							// .getString(Constant.typesStrings[i])
							.substring(1,
									typeArray.get(i).toString().length() - 1)
							.replaceAll("\"", "").split(",");
					type.areaList = areaArray
							.get(i)
							.toString()
							// .getString(Constant.typesStrings[i])
							.substring(1,
									areaArray.get(i).toString().length() - 1)
							.replaceAll("\"", "").split(",");
					// logger.v(TAG,
					// "type ="+type.type+"typeList = "+type.typeList.length);
					Constant.tMap.put(i + "", type);
					Constant.types.add(type);
				}

				return info;
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		}
		return null;

	}

	/**
	 * 查询片名接口数据
	 * 
	 * @param type
	 *            类型 type=0 电影名片 Type=1 电视剧Type=2 综艺Type=3 爱美
	 * @param start
	 *            索引开始值
	 * @param limit
	 *            最少获取多少条
	 * @param fname1
	 *            查询的字段
	 * @param fvalue
	 *            查询的字段的值
	 * @return
	 */
	public static List<MovieInfo> queryDes(String type, String start,
			String limit, String fname1, String fvalue)
	{
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("type", type);
		params.put("start", start);
		params.put("limit", limit);
		params.put("fname1", fname1);
		params.put("fvalue1", fvalue);

		try
		{
			String responseData = getPostData(QUERY_DESC, params);
			if (responseData == null)
			{
				return null;
			}
			JSONObject object = new JSONObject(responseData);
			Type listType = new TypeToken<LinkedList<MovieInfo>>()
			{
			}.getType();
			Gson gson = new Gson();
			return gson.fromJson(object.getString("db_data"), listType);
		} catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 查询片名接口数据
	 * 
	 * @param type
	 *            类型 type=0 电影名片 Type=1 电视剧Type=2 综艺Type=3 爱美
	 * @param start
	 *            索引开始值
	 * @param limit
	 *            最少获取多少条
	 * @return
	 */
	public static List<MovieInfo> queryDes2(String type, String start,
			String limit, String areaVaule, String typeVaule, String timeValue)
	{

		String sqlString = "select *  from video_desc  where type=" + type;
		String sqlString1 = " and genre like \"" + typeVaule + "\"";
		String sqlString2 = " and release_time like \"" + timeValue + "\"";
		String sqlString3 = " and prod_area like \"" + areaVaule + "\"";
		String sqlString4 = " order by ID DESC limit " + start + "," + limit;

		if (typeVaule == null)
		{
			sqlString1 = "";
		} else if (typeVaule.equals("") || typeVaule.equals("全部类型"))
		{
			sqlString1 = "";
		}
		if (areaVaule == null)
		{
			sqlString3 = "";
		} else if (areaVaule.equals("") || areaVaule.equals("全部地区"))
		{
			sqlString3 = "";
		}
		if (timeValue == null)
		{
			sqlString2 = "";
		} else if (timeValue.equals("") || timeValue.equals("不限"))
		{
			sqlString2 = "";
		}
		try
		{
			String responseData = getPostData2(QUERY_VIDEO2 + "?uid="
					+ Constant.UID, sqlString + sqlString1 + sqlString2
					+ sqlString3 + sqlString4);
			if (responseData == null)
			{
				return null;
			}
			JSONObject object = new JSONObject(responseData);
			Type listType = new TypeToken<LinkedList<MovieInfo>>()
			{
			}.getType();
			Gson gson = new Gson();
			return gson.fromJson(object.getString("db_data"), listType);
		} catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 搜索查询
	 * 
	 * @param start
	 * @param limit
	 * @param name
	 * @return
	 */
	public static List<MovieInfo> queryDes3(String start, String limit,
			String name)
	{

		String sqlString = "select *  from video_desc  where name_cn like \"%"
				+ name + "%\"";
		// String sqlString1 = " and genre like \"" + typeVaule + "\"";
		// String sqlString2 = " and release_time like \"" + timeValue + "\"";
		// String sqlString3 = " and prod_area like \"" + areaVaule + "\"";
		String sqlString4 = " order by ID DESC limit " + start + "," + limit;

		try
		{
			String responseData = getPostData2(QUERY_VIDEO2 + "?uid="
					+ Constant.UID, sqlString + sqlString4);
			if (responseData == null)
			{
				return null;
			}
			JSONObject object = new JSONObject(responseData);
			Type listType = new TypeToken<LinkedList<MovieInfo>>()
			{
			}.getType();
			Gson gson = new Gson();
			return gson.fromJson(object.getString("db_data"), listType);
		} catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 查詢電影的播放地址
	 * 
	 * @param type
	 * @param id
	 * @return
	 */
	public static List<MediaDownLoadLinkInfo> queryVideo(String type, String id)
	{
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("type", type);
		params.put("fname1", "video.desc_ID");
		params.put("fvalue1", id);
		params.put("fop1", "=");

		try
		{
			String responseData = getPostData(QUERY_VIDEO, params);
			JSONObject object = new JSONObject(responseData);
			Type listType = new TypeToken<LinkedList<MediaDownLoadLinkInfo>>()
			{
			}.getType();
			Gson gson = new Gson();
			return gson.fromJson(object.getString("db_data"), listType);

		} catch (JSONException e)
		{
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 充值
	 * 
	 * @param value
	 * @return
	 */
	public static boolean chargeToPhone(String value)
	{
		Logger logger = Logger.getLogger();
		HttpGet httpGet = new HttpGet(CHARGE + "?uid=" + Constant.UID
				+ "&value=" + value);
		HttpResponse httpResponse = null;
		BasicHttpParams parbaBasicHttpParams = new BasicHttpParams();
		try
		{
			logger.d(TAG, "url =" + CHARGE + "?uid=" + Constant.UID + "&value="
					+ value);
			HttpConnectionParams.setConnectionTimeout(parbaBasicHttpParams,
					10000);
			HttpConnectionParams.setSoTimeout(parbaBasicHttpParams, 10000);
			httpResponse = new DefaultHttpClient(parbaBasicHttpParams)
					.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == HttpsURLConnection.HTTP_OK)
			{
				String result = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");
				logger.v(TAG, result);
				Gson gson = new Gson();
				ChargeInfo info = gson.fromJson(result, ChargeInfo.class);
				return info.getCode().equals("0");
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 扣费 5. 手机端扣费 cChargeCell.php?uid=&type=&video_ID=&check= type 视频的类型
	 * video_ID 视频的ID check 可选参数，带入此参数仅返回手机的余额（不进行扣费）
	 * 
	 * @param value
	 * @return
	 */
	public static ChargeInfo chargeCell(String type, String videoId)
	{
		ChargeInfo info = null;
		Logger logger = Logger.getLogger();
		HttpGet httpGet = new HttpGet(CHARGECELL + "?uid=" + Constant.UID
				+ "&type=" + type + "&video_ID=" + videoId);
		HttpResponse httpResponse = null;
		BasicHttpParams parbaBasicHttpParams = new BasicHttpParams();
		try
		{
			logger.d(TAG, "url =" + CHARGECELL + "?uid=" + Constant.UID
					+ "&type=" + type + "&video_ID=" + videoId);
			HttpConnectionParams.setConnectionTimeout(parbaBasicHttpParams,
					10000);
			HttpConnectionParams.setSoTimeout(parbaBasicHttpParams, 10000);
			httpResponse = new DefaultHttpClient(parbaBasicHttpParams)
					.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == HttpsURLConnection.HTTP_OK)
			{
				String result = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");
				logger.v(TAG, result);
				try
				{
					Gson gson = new Gson();
					info = gson.fromJson(result, ChargeInfo.class);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
				
				return info;
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * http get方法获取数据
	 * 
	 * @param url
	 * @return
	 */
	private static String getData(String url)
	{
		Logger logger = Logger.getLogger();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		BasicHttpParams parbaBasicHttpParams = new BasicHttpParams();
		try
		{
			logger.d(TAG, "url =" + url);
			HttpConnectionParams.setConnectionTimeout(parbaBasicHttpParams,
					10000);
			HttpConnectionParams.setSoTimeout(parbaBasicHttpParams, 10000);
			httpResponse = new DefaultHttpClient(parbaBasicHttpParams)
					.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == HttpsURLConnection.HTTP_OK)
			{
				String result = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");
				logger.v(TAG, result);
				return result;
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * http post方法获取数据
	 * 
	 * @param url
	 * @return
	 */
	private static String getPostData(String url,
			HashMap<String, String> postData)
	{
		Logger logger = Logger.getLogger();
		HttpPost httpPost = new HttpPost(url);
		HttpResponse httpResponse = null;
		BasicHttpParams parbaBasicHttpParams = new BasicHttpParams();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (String string : postData.keySet())
		{
			params.add(new BasicNameValuePair(string, postData.get(string)));
		}
		params.add(new BasicNameValuePair("uid", Constant.UID));
		try
		{
			logger.d(TAG, "url =" + url);
			logger.d(TAG, "post data =" + params.toString());
			HttpConnectionParams.setConnectionTimeout(parbaBasicHttpParams,
					10000);
			HttpConnectionParams.setSoTimeout(parbaBasicHttpParams, 10000);
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			httpResponse = new DefaultHttpClient(parbaBasicHttpParams)
					.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == HttpsURLConnection.HTTP_OK)
			{
				String result = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");

				logger.v(TAG, result);
				return result;
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param url
	 * @param postData
	 * @return
	 */
	private static String getPostData2(String url, String postData)
	{
		Logger logger = Logger.getLogger();
		HttpPost httpPost = new HttpPost(url + "?uid=" + Constant.UID);
		HttpResponse httpResponse = null;
		BasicHttpParams parbaBasicHttpParams = new BasicHttpParams();
		try
		{
			logger.d(TAG, "url =" + url);
			logger.d(TAG, "post data =" + postData);

			HttpConnectionParams.setConnectionTimeout(parbaBasicHttpParams,
					10000);
			HttpConnectionParams.setSoTimeout(parbaBasicHttpParams, 10000);
			httpPost.setEntity(new ByteArrayEntity(postData.getBytes()));
			httpResponse = new DefaultHttpClient(parbaBasicHttpParams)
					.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == HttpsURLConnection.HTTP_OK)
			{
				String result = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");

				logger.v(TAG, result);
				return result;
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

}
